<script setup lang="ts">
import VueQrcode from 'vue-qrcode'
import { onMounted, ref, onUnmounted } from 'vue'
import { getQrcode, checkLoginStatus } from '@/api/wechat'
import { useRouter } from 'vue-router'
const router = useRouter()
const qrcode = ref({
  ticket: '',
  url: '',
})
const isExpired = ref(false)
let timer: any = null
onMounted(() => {
  handleGetQrcode()
})

const handleGetQrcode = async () => {
  isExpired.value = false
  const res = await getQrcode()
  console.log(res)
  qrcode.value = {
    ticket: res.ticket,
    url: res.url,
  }
  setTimeout(
    () => {
      isExpired.value = true
      console.log('二维码已过期')
    },
    (res.expire_seconds - 5) * 1000,
  )
  timer = setTimeout(() => {
    handleCheckLoginStatus()
  }, 1000)
}

const handleCheckLoginStatus = async () => {
  const res = await checkLoginStatus(qrcode.value.ticket)

  if (res === null) {
    timer = setTimeout(() => {
      handleCheckLoginStatus()
    }, 1000)
  } else {
    router.push({
      path: '/',
      query: {
        openid: res,
      },
    })
  }
}
onUnmounted(() => {
  clearTimeout(timer)
})
</script>

<template>
  <div class="container">
    <h1 class="title">微信扫码登录</h1>
    <div class="login-container">
      <div class="qrcode-wrapper" :class="{ expired: isExpired }">
        <vue-qrcode
          :value="qrcode.url"
          :width="200"
          type="image/png"
          :color="{ dark: '#000000', light: '#ffffff' }"
        ></vue-qrcode>
        <div v-if="isExpired" class="expired-mask">
          <button class="refresh-btn" @click="handleGetQrcode">点击刷新二维码</button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.container {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
}

.title {
  font-size: 28px;
  margin-bottom: 30px;
  color: #333;
  font-weight: 600;
}

.login-container {
  background-color: #fff;
  border-radius: 12px;
  padding: 10px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.qrcode-wrapper {
  position: relative;
  transition: all 0.3s ease;
}

.qrcode-wrapper.expired {
  opacity: 0.7;
}

.expired-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(0, 0, 0, 0.6);
  border-radius: 8px;
}

.refresh-btn {
  padding: 12px 24px;
  font-size: 16px;
  color: #fff;
  background-color: #07c160;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-weight: 500;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

.refresh-btn:hover {
  background-color: #06ae56;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(7, 193, 96, 0.3);
}

.refresh-btn:active {
  transform: translateY(0);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}
</style>
